package Thread;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class ForkAndJoin extends RecursiveTask<Long> {
    private long start;
    private long end;
    private long step=1000;
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        loopTime();
        long startTime=System.currentTimeMillis();
        //1.创建一个线程池
        ForkJoinPool pool=new ForkJoinPool();
        //2.创建一个任务
        ForkAndJoin sumTask=new ForkAndJoin(1,10000000000L);

        //3.将任务交给线程池
        ForkJoinTask<Long> task=pool.submit(sumTask);
        //4.得到结果并输出
        long result=task.get();

        long endTime=System.currentTimeMillis();
        System.out.println("计算结果"+(endTime-startTime));
        //5.关闭线程池
        pool.shutdown();
    }

    private static void loopTime() {
        long startTime=System.currentTimeMillis();
        long sum=0;
        for(long i=0;i<10000000000L;i++){
            sum+=i;
        }
        long endTime=System.currentTimeMillis();
        System.out.println("计算结果"+(endTime-startTime));
    }

    @Override
    protected Long compute() {
        long sum=0;
        if(end-start<=step){
            for(long i=start;i<=end;i++){
                sum+=i;
            }
        }else{
            long mid=(start+end)>>1;
            ForkJoinTask leftTask=new ForkAndJoin(start,mid);
            ForkJoinTask rightTask=new ForkAndJoin(mid,end);
            leftTask.fork();
            rightTask.fork();
            long leftSum= (long) leftTask.join();
            long rightSum= (long) rightTask.join();
            sum=leftSum+rightSum;
        }
        return sum;
    }

    public ForkAndJoin(long start,long end) {
        this.start = start;
        this.end = end;
    }

    public ForkAndJoin() {

    }

}


















